package com.budingge.httpuitls;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class UserAgentUtils {
	private final static String defaultUserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.11 (KHTML, like Gecko) Chrome/9.0.570.0 Safari/534.11";
	
	private static Random random = new Random();
	private static List<String> userAgents = new ArrayList<String>();
	static{
		
		try {
			Reader reader = new FileReader(new File("browser-useragent.txt"));
			BufferedReader bufferedReader = new BufferedReader(reader);
			String line = null;
			while((line = bufferedReader.readLine())!=null){
				userAgents.add(line);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			userAgents.add(defaultUserAgent);
		}
		
	}
	
	/**
	 * 随机获取userAgent
	 * @return
	 */
	public static String getRandomUserAgent() {
		return userAgents.get(random.nextInt(userAgents.size()));
	}
	
	/**
	 * 获取指定userAgent
	 * @param index
	 * @return
	 */
	public static String getUserAgent(int index){
		return index<0?userAgents.get(0):index<userAgents.size()?userAgents.get(index):userAgents.get(userAgents.size()-1);
	}

}
